const app = getApp()

Page({
  data: {
    customerOrBossId: '',
    item: {},
    token: wx.getStorageSync('token') || '',
    shopId: '',

    comment: '',
    customerOrBossId: '',
    domain: '',
    id: '',
    isLimit: '',
    logoId: '',
    marketingId: '',
    shopName:  '',
    ssidFlag:  '',
    ssidName:  '',
    ssidPassword:  '',
    state: 0,
    reviewStatus: null,
    status:  '',
    tenantName:  '',
    tenantPassword:  '',
    upLimit:  '',
    reviewStatusDesc: '',
    diaShow: 'none',
    check: false
  },
  onLoad: function (options) {
    this.setData({
      customerOrBossId: options.customerOrBossId,
      token: wx.getStorageSync('token') || '',
      shopId: options.shopId
    });
    this.getTable(1);
  },

  onUnload: function () {
    let pages = getCurrentPages();
    // prevPage 是获取上个页面的js里面的pages的所有信息，-2是上个页面，-3是上上个页面 以此类推
    let prevPage = pages[pages.length - 2];
    // 在本页面修改上一个页面的 data
    // prevPage.setData({
    //   customerOrBossId:this.data.customerOrBossId
    // })
    // wx.navigateBack({
    //   delta:1 ,//返回上一级页面
    //   // success: function() {
    //   //   prevPage.onLoad(); // 执行前一个页面的onLoad方法
    //   // }
    // })
  },
  getTable(i) {
    // i   1新  2旧
    let that = this;
    wx.showLoading({
      title: '加载中',
    });
    wx.request({
      url: 'https://test.cloudcampusapps.top:8080'+'/weChatWifiLogin/shopInfo/queryShopInfoById'+'?shopId='+that.data.shopId+'&flag='+i,//请求的url
      header: {
        "Content-Type": "application/json",
        "token": that.data.token
      },
      method: "GET",
      success:function(res){
        if(res.data.code==200){
          let item =  res.data.data
          that.setData({
            item: item,
            comment: item.comment,
            customerOrBossId: item.customerOrBossId,
            domain: item.domain,
            id: item.id,
            isLimit: item.isLimit,
            logoId: item.logoId,
            marketingId: item.marketingId,
            reviewStatusDesc: item.reviewStatusDesc,
            shopName:  item.shopName,
            ssidFlag:  item.ssidFlag,
            ssidName:  item.ssidName,
            ssidPassword:  item.ssidPassword,
            state: 0,
            reviewStatus: item.reviewStatus,
            status:  item.status,
            tenantName:  item.tenantName,
            tenantPassword:  item.tenantPassword,
            upLimit:  item.upLimit,
          })
          wx.hideLoading();
          if(item.reviewStatus==2) {
            that.showMess()
          }
        } else {
          wx.showToast({
            title: res.data.errorMsg,
            icon: 'none',
            duration: 2000
          })
        }
        wx.hideLoading();
      },
      fail:function(err){
        console.log('err=============='+err)
        wx.hideLoading()
      }
    })
  },
  formSubmit(e) { // 提交审核
    let item = e.detail.value;
    let that = this;
    let params={
      "customerOrBossId": this.data.customerOrBossId,
      "domain": item.domain,
      "id": item.id,
      "isLimit": item.isLimit,
      "logoId": item.logoId,
      "logoType": 0,
      "marketingId": item.marketingId,
      "marketingType": 0,
      "shopName": item.shopName,
      "ssidFlag": item.ssidFlag,
      "ssidName": item.ssidName,
      "ssidPassword": item.ssidPassword,
      "tenantName": item.tenantName,
      "tenantPassword": item.tenantPassword,
      "upLimit": item.upLimit,
      "state": 0
    };
    if(item.upLimit && item.upLimit!='0') {
      params.isLimit = true
    }else{
      params.isLimit = false
    }
    wx.showLoading({
      title: '保存中',
    });
    wx.request({
      url: 'https://test.cloudcampusapps.top:8080/weChatWifiLogin/shopInfo/updateShopInfoConfig',
      header: {
        "Content-Type": "application/json",
        "token": that.data.token
      },
      method: "POST",
      data: JSON.stringify(params),
      success:function(res){
        if(res.data.code==200){
          that.getTable(1);
        } else {
          wx.showToast({
            title: res.data.msg || res.data.erroeMsg,
            icon: 'none',
            duration: 2000
          })
          that.getTable(1);
        }
        wx.hideLoading();
      },
      fail:function(err){
        console.log('err=============='+err);
        wx.hideLoading();
      }
    })
  },
  tolast() {//立即回退
    let that = this;
    wx.showLoading({
      title: '取消中',
    });
    wx.request({
      url: 'https://test.cloudcampusapps.top:8080'+'/weChatWifiLogin/shopInfo/cancelShopInfoConfig'+'?shopId='+that.data.shopId,//请求的url
      header: {
        "Content-Type": "application/json",
        "token": that.data.token
      },
      method: "GET",
      success:function(res){
        if(res.data.code==200){
          that.getTable(1);
        } else {
          wx.showToast({
            title: res.data.msg || res.data.erroeMsg,
            icon: 'none',
            duration: 2000
          })
          that.getTable(1);
        }
        wx.hideLoading();
      },
      fail:function(err){
        console.log('err=============='+err)
        wx.hideLoading()
      }
    })
  },
  toCheck() {
    this.setData({
      diaShow: 'block'
    });
  },
  checkSubmit(e) {
    let item = e.detail.value;
    let that = this;
    let params={
      "domain": item.domain,
      "tenantName": item.tenantName,
      "tenantPassword": item.tenantPassword
    };
    wx.showLoading({
      title: '保存中',
    });
    wx.request({
      url: 'https://test.cloudcampusapps.top:8080/weChatWifiLogin/shopInfo/checkApiAccount',
      header: {
        "Content-Type": "application/json"
      },
      method: "POST",
      data: JSON.stringify(params),
      success:function(res){
        if(res.data.code==200){
          that.setData({
            check: true,
            "domain": item.domain,
            "tenantName": item.tenantName,
            "tenantPassword": item.tenantPassword
          });
        }else if(res.data.code==1001){
          wx.showToast({
            title: res.data.msg || res.data.erroeMsg,
            icon: 'none',
            duration: 2000
          })
        }else {
          wx.showToast({
            title: res.data.msg || res.data.erroeMsg,
            icon: 'none',
            duration: 2000
          })
        }
        wx.hideLoading();
      },
      fail:function(err){
        console.log('err=============='+err);
        wx.hideLoading();
      }
    })
  },
  toUse() {
    let that = this;
    let params={
      "customerOrBossId": this.data.customerOrBossId,
      "domain": this.data.domain,
      "id": this.data.id,
      "isLimit": this.data.isLimit,
      "logoId": this.data.logoId,
      "logoType": 0,
      "marketingId": this.data.marketingId,
      "marketingType": 0,
      "reviewStatus": 4,
      "shopName": this.data.shopName,
      "ssidFlag": this.data.ssidFlag,
      "ssidName":this.data.ssidName,
      "ssidPassword": this.data.ssidPassword,
      "state": 0,
      "tenantName": this.data.tenantName,
      "tenantPassword": this.data.tenantPassword,
      "upLimit": this.data.upLimit
    };
    wx.showLoading({
      title: '保存中',
    });
    wx.request({
      url: 'https://test.cloudcampusapps.top:8080/weChatWifiLogin/shopInfo/queryWeiUser',
      header: {
        "Content-Type": "application/json",
        "token": that.data.token
      },
      method: "POST",
      data: JSON.stringify(params),
      success:function(res){
        if(res.data.code==200){
          that.setData({
             diaShow: 'none'
          });
          that.getTable(1);
        }else if(res.data.code==1001){
          that.setData({
           check: true
          });

        }else {
          wx.showToast({
            title: res.data.msg || res.data.erroeMsg,
            icon: 'none',
            duration: 2000
          })
          that.getTable(1);
        }
        wx.hideLoading();
      },
      fail:function(err){
        console.log('err=============='+err);
        wx.hideLoading();
      }
    })
  },
  showMess() {
    // let obj = JSON.parse(this.data.comment);
    let obj = this.data.comment;
    let s1 = (obj.reviewInfo[0].status?obj.reviewInfo[0].reviewerColumnDesc :'')+(obj.reviewInfo[1].status?'、'+obj.reviewInfo[1].reviewerColumnDesc :'')+(obj.reviewInfo[2].status?'、'+obj.reviewInfo[2].reviewerColumnDesc :'')+(obj.reviewInfo[3].status?'、'+obj.reviewInfo[3].reviewerColumnDesc:'');
    let str = '审批负责人：'+obj.reviewer+'提醒您，您的：\n'+(s1?s1:'申请内容')+'违反绿色健康微信环境的要求，审核被驳回;'+(obj.reviewerContent&&obj.reviewerContent.length?('审核批注为：'+obj.reviewerContent):'');
    wx.showModal({
      title: '审批单号：'+obj.versionNo,
      content: str,
      showCancel: false,
      success (res) {
        if (res.confirm) {
          console.log('用户点击确定')
        }
      }
    })
  },
  change(e) {
    let state = 0
    if(this.data.state==0){state=1}
    this.setData({
      state: state
    })
  },
  bindUpload: function (e) {
    // console.log('bindUpload', e, e.target.dataset.type);   //  0==logo;1==image
    let type = e.target.dataset.type;
    var that = this;
    let url = 'https://test.cloudcampusapps.top:8080'+'/weChatWifiLogin/vFilePhysicsInfo/uploadServiceLogo'+ '?isLogo='+type+'&shopId='+this.data.id;
    wx.chooseImage({
      count:  1, // 默认3
      sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        for (var i = 0; i < tempFilePaths.length; i++) {
          wx.uploadFile({
            url: url,
            filePath: tempFilePaths[i],
            name: "file",
            header: {
              "content-type": "multipart/form-data"
            },
            success: function (res) {
              // console.log('res', JSON.parse(res.data).data.data  )
              if (res.statusCode == 200) {
                wx.showToast({
                  title: "上传成功",
                  icon: "none",
                  duration: 1500
                })
                if(type==0){
                  that.setData({
                    logoId: JSON.parse(res.data).data.data
                  })
                }else {
                  that.setData({
                    marketingId: JSON.parse(res.data).data.data
                  })
                }
                
              }
            },
            fail: function (err) {
              wx.showToast({
                title: "上传失败",
                icon: "none",
                duration: 2000
              })
            },
            complete: function (result) {
              console.log(result.errMsg)
            }
          })
        }
      }
    })
  },
  download(e) {
    let that = this;
    wx.showLoading({
      title: '加载中',
    });
    wx.downloadFile({
      url: 'https://test.cloudcampusapps.top:8080'+'/weChatWifiLogin/shopInfo/download'+'?shopId='+that.data.id,//请求的url
      success: res => {
        console.log('resdownloadFile',res)
        const filePath = res.tempFilePath;
        wx.saveFile({
          tempFilePath:filePath,
          filePath: wx.env.USER_DATA_PATH+'/'+'顾客清单.xlsx',
          success: result => {
            console.log('resultsaveFile', result.savedFilePath)
            const openFilePath = result.savedFilePath;
            wx.openDocument({ 
              filePath: openFilePath,
              fileType: "xlsx",
              success: result => {
                console.log("打开文档成功");
                wx.hideLoading();
              },
              fail: result => {
                console.log(result);
                wx.hideLoading();
              }
            });
          }
        });
      }
    });
  },
  rangePass(e) {
    let pasArr = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','_','-','$','%','&','@','+','!'];
    let password = '';
    let pasArrLen = pasArr.length;
    for (let i=0; i<8; i++){
      let x = Math.floor(Math.random()*pasArrLen);
      password += pasArr[x];
    }
    this.setData({
      ssidPassword: password
    })
  },
  changeLimit() {
    console.log('1')
    let isLimit = false
    if(this.data.isLimit){isLimit=false}else {isLimit=true}
    this.setData({
      isLimit: isLimit
    })
  }


})
